package trss.webapp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import trss.model.Torrent;
import trss.model.User;
import trss.service.TorrentManager;
import trss.service.UserManager;

@Component
@Controller
@RequestMapping("/rss/**")
public class RssController {
    private static final Logger logger = LoggerFactory.getLogger(RssController.class);
    TorrentManager torrentManager;
    UserManager userManager;
    int channelLength = 20;
    /**
     * @param torrentManager the torrentManager to set
     */
    @Autowired
    public void setTorrentManager(TorrentManager torrentManager) {
        this.torrentManager = torrentManager;
    }
    /**
     * @param userManager the userManager to set
     */
    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
    
    /**
     * @return the channelLength
     */
    public int getChannelLength() {
        return channelLength;
    }
    /**
     * @param channelLength the channelLength to set
     */
    @Value("#{appProperties.get('channelLength')}")
    public void setChannelLength(int channelLength) {
        this.channelLength = channelLength;
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    @RequestMapping(value = "/rss/{userId}", method = RequestMethod.GET)
    public String list(@PathVariable Long userId, ModelMap modelMap) {
        
        User user = userManager.get(userId);
        List<Torrent> torrents = torrentManager.getTorrents(user , channelLength );
        modelMap.addAttribute("torrents", torrents);
        modelMap.addAttribute("user", user);
        return "rssFeed";
    }
}
